from django.conf import settings
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import ListAPIView,RetrieveAPIView,CreateAPIView,\
    UpdateAPIView

from random import randint
from django_redis import get_redis_connection

from meiduo_mall.libs.yuntongxun.sms import CCP
from threading import Thread
from celery_tasks.sms_code.tasks import send_sms_code
from users.models import User
from users.serializers import UserSerializers, UserShowSerializers, UserEmailSerializers
from itsdangerous import TimedJSONWebSignatureSerializer as TJS

# Create your views here.


# 实现多线程操作
# def send_sms_code(mobile,sms_code):
#     print(11111111)
#     ccp = CCP()
#     ccp.send_template_sms(mobile,[sms_code,'5'],1)



class SMS_Code_View(APIView):
    '''发送短信'''

    # mobile－通过路径传过来的参数
    def get(self, request, mobile):
        # １，获取前端数据
        # ２，验证手机号格式
        # 手机号通过路径的形式传递过来，在路径中通过正则匹配
        # 判断前端的请求时间间隔是否在６０ｓ之内
        # 建立连接
        conn = get_redis_connection('sms_code')
        # 60s判断
        flag = conn.get('sms_code_flag_%s' % mobile)
        if flag:
            return Response({'error': '请求过于频繁'}, status=403)

        # ３，生成短信验证码
        sms_code = '%06d' % randint(0, 999999)
        print('验证码是：%s' % sms_code)

        # 通过连接对象生成管道对象
        pl = conn.pipeline()

        # ４，保存短信　　redis缓存数据库 string
        # 写入缓存数据库中
        # 1-ｋｅｙ值－接收到的手机号作为key值　２，－value值－短信内容　３，－有效期时间
        pl.setex('sms_code_%s' % mobile, 300, sms_code)
        # 写入一个标志数据
        pl.setex('sms_code_flag_%s' % mobile, 60, 2)
        # 将指令通过管道传递给redis
        pl.execute()
        # ５，发送短信
        # ccp = CCP()
        # ccp.send_template_sms(mobile,[sms_code,'5'],1)

        # 线程异步执行发送短信的方法
        # t = Thread(target=send_sms_code,kwargs={'mobile':mobile,'sms_code':sms_code})
        # t.start()

        # 使用celery
        send_sms_code.delay(mobile,sms_code)

        # ６，结果返回
        return Response('OK')


class UserNameView(APIView):
    # 用户名判断是否重复
    def get(self,request,username):
        count = User.objects.filter(username=username).count()

        return Response(
            {'count':count}
        )


class MobileView(APIView):
    # 判断手机号是否重复
    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()

        return Response(
            {'count':count}
        )


class UserView(CreateAPIView):
    # 用户注册
    serializer_class = UserSerializers



class UserShowView(RetrieveAPIView):
    '''展示用户信息'''

    serializer_class = UserShowSerializers
    queryset = User.objects.all()

    # 重写get_object方法
    def get_object(self):

        return self.request.user


class UserEmailView(UpdateAPIView):
    '''保存更新邮箱'''

    serializer_class = UserEmailSerializers

    def get_object(self):
        return self.request.user


class UserEmailVifyView(APIView):
    '''邮箱验证'''

    def get(self,request):

        # 1,获取前端数据
        token = request.query_params.get('token')
        # 2,解密token
        tjs = TJS(settings.SECRET_KEY,300)
        try:
            data = tjs.loads(token)
        except:
            return Response({'errors':'错误的token'},status=400)
        # 3,获取解密后的用户数据
        username = data.get('username')

        # 4,根据用户名查询用户对象
        user = User.objects.get(username=username)
        # 5,更新用户邮箱验证状态
        user.email_active = True
        user.save()
        # 6,返回验证状态
        return Response({'email_active':user.email_active})
